/*
 * Copyright 2019-2023 the original author or authors.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.lingz.manager.common.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @author John <engineerhe@foxmail.com>
 * @since JDK 1.8
 */
public class ZipUtil {
    /**
     * 创建压缩文件，返回压缩文件名
     * @param zipFileName
     * @param fileList
     * @param zipPath
     * @return
     */
    public String createZipFile(String zipFileName, List<String> fileList, String zipPath) {
        ZipOutputStream zos = null;
        try {
            String savePath = zipPath;//压缩包路径
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //压缩文件
            zos = new ZipOutputStream(new FileOutputStream(savePath + zipFileName));
            zipFile(fileList, zos);
            return savePath;//如果需求，可以没有返回值
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zos != null) {
                try {
                    zos.flush();
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 压缩文件
     *
     * @param datas
     * @param zos
     * @throws IOException
     */
    private void zipFile(List<String> datas, ZipOutputStream zos) throws IOException {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                String at = datas.get(i);
                //文件读取到文件流中
                URL url = new URL(at);
                URLConnection connection = url.openConnection();
                InputStream fis = connection.getInputStream();

                //压缩文件名称
                String zippath = File.separatorChar + (at.substring(at.lastIndexOf("/") + 1, at.length()));
                zos.putNextEntry(new ZipEntry(zippath));//压缩文件名
                //把流中文件写到压缩包
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                fis.close();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (filePath.endsWith(File.separator)) {
                temp = new File(filePath + tempList[i]);
            } else {
                temp = new File(filePath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                deleteFile(filePath + "/" + tempList[i]);// 先删除文件夹里面的文件
                deleteFile(filePath + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
    public void compress(HttpServletResponse response, ArrayList<File> fileList){
        try {
            ServletOutputStream fileOut = response.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(fileOut);
            Iterator iterator = fileList.iterator();
            while (iterator.hasNext()){
                File file = (File) iterator.next();
                ZipEntry ze = new ZipEntry(file.getName());
                out.putNextEntry(ze);
                InputStream stream = new FileInputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    out.write(buffer, 0,bytesRead);
                }
                out.closeEntry();
                stream.close();
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public void unzip(File  srcFile,String destDirPath) throws Exception{
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile, Charset.forName("gbk"));
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if(!targetFile.getParentFile().exists()){
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("解压文件失败", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
